import Taro, { Component, useState, useEffect } from '@tarojs/taro';
import { View, Button, Text, Image } from '@tarojs/components';
import Address from '../../static/user/icon_bianzu8.png';
import exchange from '../../static/user/icon_bianzu7.png';
import { memberCardInfo, update } from '../../services/user';
import { getUserCardCount } from '../../services/electronicCard';

import Head from '../../static/user/icon_head.png';
import Money from '../../static/user/b0b58b1a086eb31261cfd0c21c14bbe.png';
import Next from '../../static/user/icon_next.png';
import Order from '../../static/user/icon_bianzu1.png';
import Record from '../../static/user/icon_bianzu.png';
import cartcode from '../../static/user/icon_bianzu3.png';
import card from '../../static/user/icon_bianzu10.png';
import customer from '../../static/user/icon_bianzu4.png';
import apply from '../../static/user/icon_bianzu6.png';
import mark from '../../static/user/mark.png';
import iconclose from '../../static/public/icon-close.png';
import myOrder from '../../static/user/icon_bianzu9.png';
import vipsj from '../../static/user/vip-sj.png';
import vipqy from '../../static/user/vip-qy.png';
import vipb from '../../static/user/vip-b.png';
import vip from '../../static/user/vip.png';
import { isLogin, fullImgUrl } from '../../utils/utils';


import './index.scss';

function User(props) {
  const [bpic, setBpic] = useState(''); // 判断兑换类型
  const uerInfo = Taro.getStorageSync('userInfo');
  const [qpic, setQpic] = useState(''); // 判断兑换类型
  const [BgVip, setBgVip] = useState(''); // 判断兑换类型
  const [txVip, setTxVip] = useState(''); // 判断兑换类型
  const [cardCount, setCardCount] = useState(0); // 卡券数量

  const { userInfo = null } = props;
  useEffect(() => {
    // 设置卡数量
    setCardCount(Taro.getStorageSync('card_count'));
    const pic = Taro.getStorageSync('MemberPic');
    if (uerInfo.card_level == 1) {
      setBgVip(vipsj)
    } else if (uerInfo.card_level == 2) {
      setBgVip(vipqy)
    }
    if (uerInfo.member_level == 1) {
      setTxVip(vip)
    } else if (uerInfo.member_level == 2) {
      setTxVip(vipb)
    }
    pic.list.forEach(ele => {
      if (ele.key == "personal_member_benefit") {
        setQpic(ele.path)

      }
      if (uerInfo.member_level == 0 && ele.key == "member_zero_binding_pic") {

        setBpic(ele.path)
      } else if (uerInfo.member_level == 1 && ele.key == "personal_member_one_pic") {
        setBpic(ele.path)
      } else if (uerInfo.member_level == 2 && ele.key == "personal_member_two_pic") {

        setBpic(ele.path)

      }
    });
  }, []);
  const userLevel = ['VIP1', 'VIP3', 'VIP2'];
  const [popUp, setPopUp] = useState();
  function consult() {
    const mobile = Taro.getStorageSync('setting').mobile;
    Taro.showModal({
      title: '立即拨打',
      content: mobile,
    }).then(res => {
      if (res.confirm) {
        Taro.makePhoneCall({
          phoneNumber: mobile,
        });
      }
    });
  }

  function checkIsLogin() {
    if (!Taro.getStorageSync('token') || !Taro.getStorageSync('userInfo')) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/login/index',
      });
      return false;
    }
    return true;
  }

  function goCustomizes() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/agent_customizes/index',
      });
    }
  }
  function goExchangeCard() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/card-record/index',
      });
    }
  }
  function goElectronicCard() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/electronic-card/index',
      });
    }
  }

  function goCouponCard() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: `/subPacKagebWork/pages/cart/index`
      })
    }
  }

  function goApplyRecord() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/card-record/index?type=1',
      });
    }
  }

  function goExchangeRecord() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/used-card-record/index',
      });
    }
  }
  function govipRecord() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/vip-record/index',
      });
    }
  }
  function goagent() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/agent-list/index',
      });
    }
  }
  function goturnoveRecord() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/turnove-record/index',
      });
    }
  }
  function goAgentDatasta() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/agent-Datasta/index',
      });
    }
  }


  function goUserInfo() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/pages/info/index',
      });
    }
  }

  function goMyOrder() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/pages/my-order/index',
      });
    }
  }

  function goMyAddress() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/my-address/index',
      });
    }
  }
  function goMyApplyInvoice() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/my-apply-invoice/index',
      });
    }
  }
  function goLogin() {
    Taro.navigateTo({
      url: '/subPackageWork/pages/login/index',
    });
  }

  function goStorageRecord(type) {
    // 0 入库 1 出库
    Taro.navigateTo({
      url: `/subPackageWork/pages/storage-record/index?type=${type}`,
    });
  }

  function goPerformance() {
    Taro.navigateTo({
      url: '/subPackageWork/pages/performance/index',
    });
  }

  function goagentremarks() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/agentremarks/index',
      });
    }
  }
  function goApplyCard() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/apply/index',
      });
    }
  }
  //申领会员卡
  function goApplyMemberCard() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/apply-member-card/index',
      });
    }
  }
  function scan() {
    if (!this.state.userInfo) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/login/index',
      });
    } else {
      let self = this;
      Taro.scanCode({
        onlyFromCamera: true,
        success(res) {
          if (res.result.slice(0, 2) === '00') {
            // Taro.setStorageSync('card_no', res.result);
            // Taro.navigateTo({
            //   url: `/subPackageWork/pages/exchange/index?type=coupon`,
            // });
          } else {
            memberCardInfo({
              card_no: res.result.trim(),
            }).then(data => {
              Taro.showToast({
                title: data,
                icon: 'none',
              });
            });
          }
        }, fail(err) {
          Taro.showToast({
            title: '无效条形码',
            icon: 'none',
          });
        }


      });
    }
  };

  function goDingzhi() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPackageWork/pages/customized/index?id=1&showBtn=1',
      });
    }
  }
  function goApplyInvoice() {
    if (checkIsLogin()) {
      Taro.navigateTo({
        url: '/subPacKagebWork/pages/batch-apply-invoice/index',
      });
    }
  }
  function subscribe() {
    if (checkIsLogin()) {
      Taro.requestSubscribeMessage({
        tmplIds: ['dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ', 'm_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ'],
        complete: function (res) {
          Taro.showToast({
            title: res.errMsg,
            icon: 'none',
          });
        },
        success: function (res) {
          Taro.showToast({
            title: "success",
            icon: 'none',
          });
        },
        fail: function (res) {
          Taro.showToast({
            title: "error",
            icon: 'none',
          });
        }
      });
    }
  }
  function clickVipMsg() {
    setPopUp(true)
  }
  function hindenpopUp() {
    setPopUp(false)
  }

  function getUserProfile() {
    console.log(this.state.userInfo)
    if (checkIsLogin()) {
      let id = userInfo.id;
      let data = {
        id: id
      }
      console.log(data)
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          data.nickname = res.userInfo.nickName;
          data.avatar = res.userInfo.avatarUrl
          update(data).then((res) => {
            Taro.setStorageSync('userInfo', res.user);
            Taro.showToast({
              title: '更新成功',
              icon: 'none'
            })
            return Taro.reLaunch({ url: '/pages/user/index' });
          })
        }
      })
    }
  }

  return (
    <View className='user'>
      <View className='header'>
        {!userInfo ? (
          <View className='header-box' onClick={goLogin}>
            <View className='msg1'>
              <Image src={Head} className='noCover' />
            </View>
            <View className='tip'>点击登录</View>
          </View>
        ) : null}
        {/* {userInfo && userInfo.nickname === '微信用户' ? (
          <View className='header-box' onClick={getUserProfile}>
            <View className='msg1'>
              <Image src={Head} className='noCover' />
            </View>
            <View className='tip'>授权微信昵称</View>
          </View>
        ) : null} */}
        {/* {userInfo && userInfo.nickname != '微信用户' ? () : null} */}
        <View className='header-box'>
          <Image className='msg1' src={txVip}>
            <Image src={userInfo.avatar} className='noCover' />
            <View className="update" onClick={goUserInfo}>编辑</View>
          </Image>
          <View className='msg'>
            <View className='top'>
              <View className='nickname'>{userInfo.nickname}</View>
              {uerInfo.card_level != 0 ? (
                <View className='vip'>
                  <Image src={BgVip} alt='vip' className='bg' />
                </View>
              ) : (
                ''
              )}

            </View>
            {userInfo.mobile && <View className="mobile">{userInfo.mobile}</View>}
          </View>
          <View className='space'></View>
        </View>
      </View>
      <View className="borderDiv">
        <View className="flexIcon">
          {userInfo && userInfo.level ? (
            <View className="LinkParent" onClick={goPerformance}>
              <View>
                <Image src={myOrder} className='icon' />
                <View className="tittle">我的记录</View>
                <View className="pstittle">查看业绩</View>
              </View>
            </View>
          ) : (
            ''
          )}
          {userInfo && userInfo.level ? (
            <View className="longString"></View>
          ) : (
            ''
          )}
          <View className="LinkParent" onClick={goMyOrder}>
            <View>
              <Image src={Order} className='icon' />
              <View className="tittle">我的订单</View>
              <View className="pstittle">查看订单</View>
            </View>
          </View>
          <View className="longString"></View>
          {/* 老卡券 */}
          {/* <View className="LinkParent" onClick={goExchangeCard} >
            <View>
              <Image src={cartcode} className='icon' />
              <View className="card-count">{cardCount}</View>
              <View className="tittle">我的卡券</View>
            </View>
          </View> */}
          <View className="LinkParent" onClick={goElectronicCard} >
            <View>
              <Image src={card} className='icon' />
              {cardCount > 0 ? (<View className="card-count">{cardCount}</View>) : null}
              <View className="tittle">我的卡包</View>
            </View>
          </View>
          <View className="longString"></View>
          <View className="LinkParent" onClick={goDingzhi}>
            <View>
              <Image src={Record} className='icon' />
              <View className="tittle">vip定制</View>
              <View className="pstittle">vip定制通道</View>
            </View>
          </View>
          <View className="longString"></View>
          {userInfo && userInfo.level === 2 ? (
            <View className="LinkParent" onClick={goExchangeRecord}>
              <View>
                <Image src={exchange} className='icon' />
                <View className="tittle">我的兑换记录</View>
                {/* <View className="pstittle">查看订单</View> */}
              </View>
              {/* <View className="line"></View> */}
            </View>
          ) : (
            <View className="LinkParent" onClick={goCouponCard}>
              <View>
                <Image src={Money} className='icon' />
                <View className="tittle">购物车</View>
                {/* <View className="pstittle">查看订单</View> */}
              </View>
              {/* <View className="line"></View> */}
            </View>
          )}
        </View>
      </View>
      {userInfo && userInfo.member_level ? (
        <View className="card" style={`background-image: url(${fullImgUrl(bpic)})`}>
          <Text className="twoEight">{userInfo.member_level == 0 ? '普通' : userInfo.member_level == 1 ? 'VIP ' : userInfo.member_level == 2 ? '红宝石' : ''}贵宾会员</Text>
          <Text className="twoFour">No.{userInfo.card_no == null ? '' : userInfo.card_no}</Text>
          <View className="flexLayout distance">
            <View className="twoFour1">￥</View>
            <View className="threeSix">{userInfo.balance}</View>
            <View className="twoFour2">抵扣额度</View>
          </View>
          <View>
            <Image src={mark} className='iconvip' onClick={clickVipMsg} />
            <Text className="twoFour3" onClick={clickVipMsg}>会员权益</Text>
            <View></View>
          </View>
        </View>
      ) : (
        ''
      )}

      <View className="bottom-lang">
        {userInfo ? (
          <View className="langLine" onClick={goMyAddress}>
            <View className="iconAndtext">
              <View >
                <Image src={Address} className='icon' />
              </View>
              <View className="tittle">收货地址管理</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {/* {userInfo && userInfo.level == 2 ? (
          <View className="langLine" onClick={goExchangeRecord}>
            <View className="iconAndtext">
              <View >
                <Image src={exchange} className='icon' />
              </View>
              <View className="tittle">我的兑换记录</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
            ''
          )} */}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goagentremarks}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">我的个人信息</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && (userInfo.level == 1 || userInfo.level == 2) ? (
          <View className="langLine" onClick={goApplyCard}>
            <View className="iconAndtext">
              <View >
                <Image src={apply} className='icon' />
              </View>
              <View className="tittle">申领兑换卡</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={scan}>
            <View className="iconAndtext">
              <View >
                <Image src={cartcode} className='icon' />
              </View>
              <View className="tittle">扫码激活会员卡</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goCustomizes}>
            <View className="iconAndtext">
              <View >
                <Image src={cartcode} className='icon' />
              </View>
              <View className="tittle">代理商定制页面</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {/* {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goApplyMemberCard}>
            <View className="iconAndtext">
              <View >
                <Image src={cartcode} className='icon' />
              </View>
              <View className="tittle">申领会员卡</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
            ''
          )} */}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={govipRecord}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">会员卡激活列表</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && userInfo.card_level == 1 ? (
          <View className="langLine" onClick={goagent}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">代理商列表</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goturnoveRecord}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">会员流水列表</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goAgentDatasta}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">查看汇总数据</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {/* {userInfo? (
          <View className="langLine" onClick={goMyApplyInvoice}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">发票簿管理</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
            ''
          )} */}
        {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={goApplyInvoice}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">申请发票</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
        {/* {userInfo && userInfo.card_level > 0 ? (
          <View className="langLine" onClick={subscribe}>
            <View className="iconAndtext">
              <View >
                <Image src={Order} className='icon' />
              </View>
              <View className="tittle">订阅授权</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )} */}
        {userInfo && (userInfo.level == 0 || userInfo.level == 1) ? (
          <View className="langLine" onClick={consult}>
            <View className="iconAndtext">
              <View >
                <Image src={customer} className='icon' />
              </View>
              <View className="tittle">客服咨询</View>
            </View>
            <View>
              <Image src={Next} className='next' />
            </View>
          </View>
        ) : (
          ''
        )}
      </View>

      {popUp == true ? (
        <View className="popUp"></View>
      ) : (
        ''
      )}
      {popUp == true ? (
        <View className="matter">
          <Image className="matter-img" src={fullImgUrl(qpic)}></Image>
          <Image className="close" onClick={hindenpopUp} src={iconclose}></Image>
        </View>
      ) : (
        ''
      )}









      {/* {!userInfo || (userInfo && !userInfo.is_admin) ? (
        <View className='Column'>
          {userInfo && userInfo.level ? (
            <ColumnBox
              name='我的记录'
              value='Performance'
              onPerformance={goPerformance}
              icon={Wallet}
              tip='查看记录'
              isNext={true}
            />
          ) : (
            // <ColumnBox name="我的积分" value="Integral" onIntegral={integral} icon={Integral} num={userInfo ? userInfo.integral + '' : '0'} />
            ''
          )}
          <View className='specialLine'>
            <ColumnBox
              name='我的订单'
              value='Order'
              onOrder={goMyOrder}
              icon={Order}
              tip='查看订单'
              isNext={true}
            />
            <View className='line'></View>
            <ColumnBox
              name='收货地址管理'
              value='Address'
              onAddress={goMyAddress}
              icon={Address}
              isNext={true}
            />
          </View>
          <View className='specialLine'>
            <ColumnBox
              name='我的卡券'
              value='ExchangeCard'
              onExchangeCard={goExchangeCard}
              icon={Money}
              number={
                userInfo ? (userInfo.level === 1 ? (userInfo.card_num || 0) + ' ' : ' ') : ' '
              }
              isNext={true}
            />
            <View className='line'></View>

            {userInfo && userInfo.level === 1 && (
              <ColumnBox
                name='我的优惠券'
                value='ExchangeCard'
                onExchangeCard={goCouponCard}
                icon={Money}
                number={
                  userInfo ? (userInfo.level === 1 ? (userInfo.coupon_num || 0) + ' ' : ' ') : ' '
                }
                isNext={true}
              />
            )}
            {userInfo && userInfo.level === 1 && <View className='line'></View>}
            <ColumnBox
              name='我的兑换记录'
              value='ExchangeRecord'
              onExchangeRecord={goExchangeRecord}
              icon={Record}
              isNext={true}
            />
            {userInfo && userInfo.level === 1 && <View className='line'></View>}
            {userInfo && userInfo.level === 1 && (
              <ColumnBox
                name='申领卡券'
                value='ApplyRecord'
                onApplyRecord={goApplyRecord}
                icon={Record}
                isNext={true}
              />
            )}
          </View>
          <ColumnBox
            value='Consult'
            name='客服咨询'
            onConsult={consult}
            icon={Consultation}
            isNext={true}
          />
          {userInfo && userInfo.level === 1 && (
            <View className='apply-card-wrapper'>
              <View className='apply-card' onClick={goApplyCard}>
                申领卡
              </View>
            </View>
          )}
        </View>
      ) : (
        // 超级代理端
        <View className='Column'>
          <View className='specialLine'>
            <ColumnBox
              name='出库记录'
              value='OutRecord'
              onOutRecord={() => {
                goStorageRecord(1);
              }}
              icon={Out}
              tip='查看'
              isNext={true}
            />
          </View>
          <View className='specialLine'>
            <ColumnBox
              name='入库记录'
              value='PutRecord'
              onPutRecord={() => {
                goStorageRecord(0);
              }}
              icon={Put}
              tip='查看'
              isNext={true}
            />
          </View>
          <ColumnBox
            value='Consult'
            name='客服咨询'
            onConsult={consult}
            icon={Consultation}
            isNext={true}
          />
        </View>
      )} */}
    </View>
  );
}

User.config = {
  navigationBarTitleText: '我的',
};

export default User;
